<template>
  <div>
    <unit-table
      ref="unitTable"
      :columns="this.$staticMenu.AreaColumns"
      :params="tableParams"
      :size="pageSize"
      selectType="checkbox"
      :sizeOptions="pageSizeOptions"
      :type="tableType"
      :url="tableUrl"
      rowKeyName="id"
      :rowSelection="rowSelection"
      @onSelect="tableOnSelect"
      :cityInfos2="cityInfos"
    >
      <!-- 补充搜索条件 -->
      <a-row slot="searchCri">

        <a-col :span="3">
          <a-select
            class="searchCriteria"
            @change="handleNeedChange"
            v-model="tableParams.levelType"
            placeholder="请选择检索层级"
          >
            <a-select-option :value=null>
              全部
            </a-select-option>
            <a-select-option value='1'>
              1
            </a-select-option>
            <a-select-option value="2">
              2
            </a-select-option>
            <a-select-option value="3">
              3
            </a-select-option>
            <a-select-option value="4">
              4
            </a-select-option>
          </a-select>
        </a-col>
        <a-col :span="5">
          <a-input v-model="tableParams.city" class="searchCriteria" placeholder="城市名" />
        </a-col>
        <a-col :span="3">
          <a-input v-model="tableParams.cityCode" class="searchCriteria" placeholder="城市编码"/>
        </a-col>
        <a-col :span="3">
          <a-input v-model="tableParams.province" class="searchCriteria" placeholder="父级名称"/>
        </a-col>
        <a-col :span="3">
          <a-input v-model="tableParams.remarks" class="searchCriteria" placeholder="标记"/>
        </a-col>
        <a-col :span="5" style="text-align: right;">
          <a-button type="primary" @click="criteriaSearch">
            <a-icon type="search"/>
            查询
          </a-button>
          <a-button @click="clearCriteria">
            <a-icon type="sync"/>
            重置
          </a-button>
        </a-col>
      </a-row>
      <!-- end -->
      <!-- 补充表格操作 -->
      <div slot='tableAct' class="actionBtn">
        <!--      <a-button  type="primary" @click="addNeeds">-->
        <!--        <a-icon type="plus"/>-->
        <!--        新增需求-->
        <!--       </a-button>-->
        <a-button v-if="this.isManager" type="primary" @click="newArea">
          <a-icon type="check"/>
          添加
        </a-button>
      </div>
      <!-- end -->
      <!-- 补充表格每行的操作 -->
      <span slot="tableRowAct" slot-scope="props">
        <a>
          <span class="ant-tag" @click="editArea(props.record.cityCode)">
            <a-icon type="download"/> 修改
          </span>
        </a>
         <a>
          <span class="ant-tag" @click="delArea(props.record.cityCode)">
            <a-icon type="delete"/> 删除
          </span>
        </a>
        <!--        <a-divider type="vertical" v-if="props.record.status=='审批通过'" />
                <a v-if="props.record.status=='审批通过'">
                  <span class="ant-tag ant-tag-green" @click="addHost(props.record)">
                    <a-icon type="plus"/> 创建
                  </span>
                </a>-->
      </span>
    </unit-table>
    <modal
      ref="areaModalForm"
      :title="modalTitle"
      :visible="modalVisible"
      @cancel="handleCancel"
      @ok="handleOk"
    />
  </div>
</template>

<script>
import { GETCITYINFOLIST, GETCITYINFOS, REMOVECITYINFOS, NEEDACCEPT, NEEDREJECT } from '@/../static/js/apis.js'
import unitTable from '@/common/tableCheck'
import global from '@/../static/global.vue'
import modal from './areaModal'
import moment from 'moment'
export default {
  inject: ['reload'], // 注入App里的reload方法
  name: 'AllUnit',
  components: {
    unitTable,
    modal
  },

  computed: {
    //  判断是否管理员
    isManager() {
      return global.isManager(global.SYS_BUSINSESS_MANAGE)
      //  return localStorage.getItem('role').indexOf('0') > -1
    },
    rowSelection() {
      return {
        selectedRowKeys: this.tableSelectedKeys || [], // 选中行的key当props传值过来时，默认选中
        selectedRows: [], // 选中行的内容
        onChange: (selectedRowKeys, selectedRows) => {
          this.rowSelection.selectedRowKeys = selectedRowKeys
          this.rowSelection.selectedRows = selectedRows
          this.tableOnSelect(selectedRowKeys, selectedRows)
        },
        getCheckboxProps: record => ({
          props: {
            disabled: record.status !== '未审批' // Column configuration not to be checked
          }
        })
      }
    }
  },
  data() {
    return {
      tableSelectedKeys: [],
      tableUrl: GETCITYINFOLIST.url, // 调用表格组件，必须参数，后台数据接口
      tableType: GETCITYINFOLIST.type, // 调用表格组件，必须参数，后台方法方法（get，post）
      pageSize: 15,
      pageSizeOptions: ['15', '20', '40'],
      /* modal参数*/
      modalTitle: '', // modal标题
      modalVisible: false, // modal关闭打开控制器
      /* 调用表格组件，可选参数，其他相关搜索条件*/
      tableParams: {
        levelType: undefined,
        cityCode: '',
        city: '',
        province: '',
        remarks: ''
      },
      pagination: {
        page: 1,
        limit: 15
      },
      time: [],
      timeReport: [],
      userRole: localStorage.getItem('role'),
      name: '',
      id: '',
      demandyear: '',
      demandclassify: '',
      tabType: '',
      str: '',
      reaModalVisible: false,
      reaModalTitle: '',
      curVal: '',
      rejModalVisible: false,
      rejModalTitle: '',
      cityInfos: []
    }
  },
  mounted() {
    if (this.$route.query.type === 'JRXQ') {
      this.tableParams.starttime = this.getNowFormatDate()
      this.time = [moment(this.getNowFormatDate(), 'YYYY/MM/DD'), moment(this.getNowFormatDate(), 'YYYY/MM/DD')]
      this.tableParams.endtime = this.getNowFormatDate()
      this.criteriaSearch()
    } else if (this.$route.query.type === 'JRXF') {
      this.tableParams.td_start = this.getNowFormatDate()
      this.tableParams.td_end = this.getNowFormatDate()
      this.timeReport = [moment(this.getNowFormatDate(), 'YYYY/MM/DD'), moment(this.getNowFormatDate(), 'YYYY/MM/DD')]
      this.criteriaSearch()
    }
  },
  methods: {
    keydown(e) {
      if (e.keyCode == 32) {
        e.returnValue = false
      }
    },
    // getVal(msg){
    //   this.str = msg;
    //   console.log("msg"+this.str)
    // },
    /* modal确定事件*/
    handleOk(e) {
      this.modalVisible = false
    },

    /* 表格checkbox选中事件*/
    tableOnSelect(selectedRowKeys, selectedRows) {
      this.tableSelectedKeys = selectedRowKeys
    },
    /* 查询按钮 */
    criteriaSearch() {
      GETCITYINFOS(
        // {page: 1, limit: '', city: this.tableParams.city, cityCode: this.tableParams.cityCode
        { keyWords: '', page: 1, limit: 99999, levelType: this.tableParams.levelType, city: this.tableParams.city, cityCode: this.tableParams.cityCode, province: this.tableParams.province, remarks: this.tableParams.remarks, sortField: '', sortOrder: ''
        },
        (res) => {
          this.cityInfos = res.list
          this.$refs.unitTable.fetch(1)
        }
      )
    },
    /* 重置按钮 */
    clearCriteria() {
      this.tableParams.classify = ''
      this.tableParams.name = ''
      this.tableParams.people = ''
      this.tableParams.starttime = ''
      this.tableParams.endtime = ''
      this.time = []
      this.tableParams.td_start = ''
      this.tableParams.td_end = ''
      this.timeReport = []
      this.tableParams.city = ''
      this.tableParams.cityCode = ''
      this.tableParams.levelType = ''
      this.tableParams.province = ''
      this.tableParams.remarks = ''
      this.$refs.unitTable.rowSelection.onChange([], [])
      this.criteriaSearch()
    },
    getNowFormatDate() {
      var date = new Date()
      var seperator1 = '-'
      var year = date.getFullYear()
      var month = date.getMonth() + 1
      var strDate = date.getDate()
      if (month >= 1 && month <= 9) {
        month = '0' + month
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = '0' + strDate
      }
      var currentdate = year + seperator1 + month + seperator1 + strDate
      return currentdate
    },

    /* 选择当前状态*/
    handleNeedChange(value) {
      this.tableParams.classify = value
    },
    handleDateChange(date, dateString) {
      this.tableParams.starttime = dateString[0]
      this.tableParams.endtime = dateString[1]
    },
    handleDateReportChange(date, dateString) {
      this.tableParams.td_start = dateString[0]
      this.tableParams.td_end = dateString[1]
    },
    newArea() {
      const self = this
      self.modalTitle = '创建生产任务'
      self.modalVisible = true
    },
    /* modal取消事件*/
    handleCancel(e) {
      this.modalVisible = false
    },
    editArea(record) {
      const self = this
      self.modalTitle = '修改城市'
      self.modalVisible = true
      GETCITYINFOS(
        // {page: 1, limit: '', city: this.tableParams.city, cityCode: this.tableParams.cityCode
        { cityCode: record },
        (res) => {
          console.log('res', res)
          // 把数据放入modal，要在form加载完成后
          self.$nextTick(() => {
            console.log('res.list[0]', res.list[0])
            self.$refs.areaModalForm.form.setFieldsValue(res.list[0])
            self.$refs.areaModalForm.value = [{ key: `${res.list[0].cityCode}`,
              label: `
              ${res.list[0].mergerName.split(',')[0]}
            ` }]
            console.log('self.val', self.$refs.areaModalForm.value, self.$refs.areaModalForm.city)
          })
        }
      )
    },
    delArea(cityCode) {
      const self = this
      self.$confirm({
        title: '确定要删除该项吗？',
        content: '',
        onOk() {
          REMOVECITYINFOS({ cityCode }, res => {
            if (res.code === '200') {
              self.$message.success(res.message)
              self.reload()
            } else self.$message.error(res.message)
          })
        }
      })
      console.log('cityCode', cityCode)
    }

  }

}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.searchCriteria {
  width: 90%;
}

.actionBtn button:not(:last-child),
.ant-row button:not(:last-child) {
  margin-right: 20px;
}
</style>
